import React, { useEffect, useState } from "react";
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Table, Popover, message } from "antd";
import request, { exportFile } from "@/utils/request";
import { CmdbContent, CmdbHeader, isAuthorized, HcpTableTooltip, BusinessBtn } from "@/components";
import moment from "moment";
import cmdbres from "@/data/cmdbres";
import hcpUtils from "@/utils/hcpUtils";
import DeleteModal from './delete';
import "./index.less"

const ClusterTemplate = ({ history, match, location }) => {
    const [biz, setBiz] = useState();
    const [searchValue, setSearchValue] = useState('');
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [row, setRow] = useState({});
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    
    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        if(!(biz && biz.cm_unid)) {
			message.warning("请确认是否创建业务！");
			return;
		}
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.querySetTemplate,
                data: {
                    bizId: biz.cm_unid
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total, 
                }));
                res.data.map((item, index) => item.key=index);
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        if(biz)
            getTableData();
    }, [biz]);

    const handleTableChange = (e) => {
        getTableData(e);
    };
    
    const columns = [
        {
            title: "ID",
            key: "id",
            dataIndex: "id",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => (
                <HcpTableTooltip
                    label="id"
                    showValue={text}
                    onClick={()=> {
                        history.push({
                            pathname: `/business/clusterTemplate/detail/${record.id}`,
                            state: {template: record}
                        })
                    }}
                />
            )  
        },
        {
            title: "模版名称",
            key: "name",
            dataIndex: "name",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "应用数量",
            key: "set_instance_count",
            dataIndex: "set_instance_count",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "创建人",
            key: "creator",
            dataIndex: "creator",
            isShow: true,
            width: 140,
        },
        {
            title: "创建时间",
            key: "createTime",
            dataIndex: "createTime",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => hcpUtils.timeConversion(text, 'YYYY-MM-DD HH:mm:ss')
        },
        {
            title: "操作",
            fixed: 'right',
            width: 100,
            render: (text, record, index) => {
                return (
                <Space key={record.resource_id}>
                    <Popover content="修改">
                        <span 
                            className="iconfont icon-edit" 
                            onClick={() => {history.push({ pathname: "/business/clusterTemplate/update", state: {biz, template: record}})}}
                        />
                    </Popover>
                    <Popover content="删除">
                        <span 
                            className="iconfont icon-delete" 
                            onClick={() => { setRow(record); setShowDeleteModal(true); }}
                        />
                    </Popover>
                </Space>
                )
            }
        } 
    ]

    const [top, setTop] = useState(88);
    return (
        <CmdbContent>
            <CmdbHeader title={'集群模板'} />
            <section className="hcp__page">
                <section className="hcp__page__container">    
                <div style={{backgroundColor: "#fff", padding: "10px"}}>  
                    <div className="affix-header">
                        <div style={{marginBottom: 10}}>
                            <BusinessBtn setBiz={setBiz} history={history}/>
                        </div>
                        <Alert style={{marginBottom: 10}}
                            message={
                                <div>
                                    集群模板可以定义业务通用的集群结构，用于 
                                    <a onClick={() => { history.push({ pathname: "/business/topology"});}}>业务拓扑</a> 
                                    中快速部署和维护集群。此功能依赖已经存在 
                                    <a onClick={() => { history.push({ pathname: "/business/serviceTemplate"});}}>服务模板</a> 。
                                </div>
                            }
                            type="info"
                            closable
                            showIcon
                        />
                        <Row style={{marginBottom: 10}}>
                        <Col span={8}>
                            <Space>
                                <Button 
                                    className="hcp_toolbar_btn" 
                                    type="primary"
                                    onClick={() => {history.push({ pathname: "/business/clusterTemplate/create", state: {biz}})}}>
                                        新建
                                </Button>
                                <Button type="primary" onClick={() => {getTableData()}} >
                                    刷新
                                </Button>
                            </Space>
                        </Col>
                        {/* <Col span={16} style={{ textAlign: "right" }}>
                            <Space>
                                <Input.Search
                                    placeholder="请输入关键字"
                                    value={searchValue}
                                    onChange={(e) => {
                                        setSearchValue(e.target.value);
                                    }}
                                    onSearch={getTableData}
                                    style={{ width: "210px" }}
                                    enterButton
                                />
                            </Space>
                        </Col> */}
                        </Row>
                    </div>
                    <Table
                        columns={columns}
                        loading={loading}
                        dataSource={tableData}
                        scroll={{ x: '100%' }}
                        pagination={{
                            showSizeChanger: true,
                            showQuickJumper: {
                            goButton: (
                                <Button style={{ margin: "0 10px" }}>确定</Button>
                            ),
                            },
                            ...pagination,
                        }}
                        onChange={handleTableChange}
                        hideSetting
                    />
                </div>
                </section>
            </section>
            <DeleteModal
                onDeleteFinish={getTableData}
                visible={showDeleteModal}
                setVisible={setShowDeleteModal}
                info={row}
            />
        </CmdbContent>
    );
};

export default ClusterTemplate;